package com.hedl.practice.diyJava.multithreading.forkJoin;

import com.hedl.practice.diyJava.multithreading.forkJoin.utils.SumTask;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

public class StudyForkJoin {
    public static void main(String[] args) {
        //创建2000个随机数组成的数组
        long[] array = new long[10000];
        long expectedSum = 0;
        for (int i = 0;i < array.length;i++){
            array[i] = random();
            expectedSum += array[i];
        }
        System.out.println("Expected sum: "+expectedSum);
        //fork/join
        ForkJoinTask<Long> task = new SumTask(array,0,array.length);
        long startTime = System.currentTimeMillis();

        /**
         * commonPool()：返回公共池实例。
         * invoke()：执行给定任务，完成后返回结果
         */
        Long result = ForkJoinPool.commonPool().invoke(task);
        long endTime = System.currentTimeMillis();
        System.out.println("Fork/join sum: "+result+" in "+(endTime - startTime)+" ms.");
    }
    static Random random = new Random(0);
    static long random(){
        return random.nextInt(10000);
    }
}
